package com.zzq.my.jetpacks.jectpackapp.net.loadCaptcha

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.aisier.architecture.base.BaseViewModel
import com.zzq.my.jetpacks.net.rxhttp.show

import kotlinx.coroutines.launch

import okhttp3.internal.EMPTY_BYTE_ARRAY


/**
 * 描述：图形验证码获取
 * 作者：zhuangzeqin
 * 时间: 2022/1/20-10:47
 * 邮箱：zzq@eeepay.cn
 * 备注:
 */
class LoadCaptchaViewModel : BaseViewModel() {
    private val mRepository by lazy {
        LoadCaptchaRepo()
    }

    //图形验证码相应的是byte 数组
    val loadCaptchaLiveData = MutableLiveData<ByteArray>()

    /**
     * 获取图形验证码
     */
    fun reqLoadCaptcha() {
        viewModelScope.launch {
            val reqLoadCaptcha = mRepository.reqLoadCaptcha()
            val byteStream = reqLoadCaptcha?.byteStream()
            byteStream?.let {
                val readStream = readStream(it)//将图片内容解析成字节数组
                loadCaptchaLiveData.value = readStream ?: EMPTY_BYTE_ARRAY
            }
        }
    }

    fun reqLoadCaptcha2() {
        viewModelScope.launch {
            mRepository.reqLoadCaptcha2().apply {
                onSuccess { response ->
                    response.body?.byteStream()?.let {
                        loadCaptchaLiveData.value = readStream(it)?:EMPTY_BYTE_ARRAY
                    }
//                    val body = response.body
//                    val byteStream = body?.byteStream()
//                    byteStream?.let {
//                        val readStream = readStream(it)//将图片内容解析成字节数组
//                        loadCaptchaLiveData.value = readStream ?: EMPTY_BYTE_ARRAY
//                    }
                }
                onFailure {
                    it.show()
                }
            }
        }
    }
}